package com.moneywelcome.goldassembly.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moneywelcome.annnotation.RedisAnnotation;
import com.moneywelcome.goldassembly.model.GoldAgreement;
import com.moneywelcome.goldassembly.model.GoldInfo;
import com.moneywelcome.goldassembly.model.RedeemRule;
import com.moneywelcome.goldassembly.model.SubscribeRule;
import com.moneywelcome.goldassembly.service.*;
import com.moneywelcome.goldfacade.GoldOperationApi;
import com.moneywelcome.goldfacade.GoldQueryApi;
import com.moneywelcome.goldfacade.dto.*;
import com.moneywelcome.goldfacade.vo.GoldTrendVo;
import com.moneywelcome.goldfacade.vo.TrendVo;
import com.moneywelcome.results.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Slf4j
@RestController
public class GoldQueryApiImpl implements GoldQueryApi {
    @Autowired
    private GoldInfoService gis;
    @Autowired
    private GoldAgreementService gas;
    @Autowired
    private RedeemRuleService rrs;
    @Autowired
    private SubscribeRuleService srs;
    @Autowired
    private GoldTrendService gts;
    @Autowired
    private GoldOperationApi goa;
    @Autowired
    private StringRedisTemplate srt;
    @RedisAnnotation
    @Override
    public Result<List<GoldInfoDto>> queryALL() {
        return Result.success(BeanUtil.copyToList(gis.list(), GoldInfoDto.class));
    }

    @Override
//    @RedisAnnotation(read = false,refresh = "com.moneywelcome.goldassembly.apiImpl.GoldQueryApiImpl.queryALL")
    @RedisAnnotation
    public Result<GoldInfoDto> queryById(Integer goldId) {
        GoldInfo goldInfo = gis.getById(goldId);
        log.info("{}",goldInfo);
        return Result.success(BeanUtil.copyProperties(goldInfo, GoldInfoDto.class));
    }

    @Override
    @RedisAnnotation
    public Result<GoldAgreementDto> queryAggre(Integer goldId) {
        log.info("开始查询{}", goldId);
        return Result.success(BeanUtil.copyProperties(gas.getOne(new QueryWrapper<GoldAgreement>().eq("gold_id", goldId)), GoldAgreementDto.class));
    }

    @Override
    @RedisAnnotation
    public Result<SubscribeRuleDto> querySubRule(Integer goldId) {
        log.info("开始查询{}", goldId);
        return Result.success(BeanUtil.copyProperties(srs.getOne(new QueryWrapper<SubscribeRule>().eq("gold_id", goldId)), SubscribeRuleDto.class));
    }

    @Override
    @RedisAnnotation
    public Result<RedeemRuleDto> queryRedeemRule(Integer goldId) {
        log.info("开始查询{}", goldId);
        return Result.success(BeanUtil.copyProperties(rrs.getOne(new QueryWrapper<RedeemRule>().eq("gold_id", goldId)), RedeemRuleDto.class));
    }

    @Override
    @RedisAnnotation
    public Result<TrendDto> queryTrend(TrendVo trendVo) {
        return Result.success(gts.queryTrend(trendVo));
    }

    /**
     * 查询当天收盘价
     *
     * @param goldId
     * @param today
     * @return
     */
    @Override
    @RedisAnnotation
    public Result<GoldTrendDto> queryTrendDay(Integer goldId, String today) {
        return Result.success(gts.queryTrendDay(goldId, today));
    }

    /**
     * 黄金实时信息
     *
     * @param goldId
     * @return
     * @throws IOException
     */

    @Override
    public Result<ProductInfoDto> getCurrentInfo(String goldId) throws IOException {
        log.info("定时任务开启{}", DateUtil.now());
        URL u = new URL("http://api.k780.com/?app=finance.gold_price&goldid=" + goldId + "&appkey=63711&sign=8b02b2d90b386bc2e9e3b117436e5ba5&format=json");
        InputStream in = u.openStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte buf[] = new byte[1024];
            int read = 0;
            while ((read = in.read(buf)) > 0) {
                out.write(buf, 0, read);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        byte b[] = out.toByteArray();
        String result = new String(b, "utf-8");
        String substring = result.substring(result.lastIndexOf("{"), result.indexOf("}") + 1);
        ProductInfoDto productInfoDto = JSONUtil.toBean(substring, ProductInfoDto.class);
        return Result.success(productInfoDto);
    }

    @Scheduled(cron = "0 0 18 * * ?")
    public void getCurrentInfoTrigger() throws IOException {
        Result<List<GoldInfoDto>> listResult = queryALL();
        listResult.getData().forEach(gold -> {
            try {
                ProductInfoDto dto = getCurrentInfo(gold.getGoldCode()).getData();
                log.info("黄金{}", dto);
                GoldTrendVo goldTrendVo = new GoldTrendVo();
                goldTrendVo.setGoldId(dto.getGoldid());
                goldTrendVo.setTrendPrice(dto.getLastPrice());
                goa.saveTrend(goldTrendVo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
